var winston = require('winston');
var mysql = require('mysql');

module.exports = function(pool, req, res, next){
	var eventId = req.params.eventId;
	var printItems = req.body.printItems;
	if(typeOf(printItems) === 'string'){
		printItems = JSON.parse(printItems);
	}
	if(eventId && printItems && printItems.length > 0){
		var feedback = [];
		var total = printItems.length;
		printItems.forEach(function(item){
			var photoId = Number.from(item.photoId);
			if(photoId === null){
				feedback.push({
					'type': 'error',
					'message': "invalid paramters: expect photoId to be number.",
					'photo_id': item.photoId,
					'copies': item.copies
				});
				if(feedback.length === total){
					doFeedback(feedback, res);
				}
				return
			}
			var copies = Number.from(item.copies) || 1;
			var params = [eventId, photoId, copies, 0, String.from(Date.now())];
			var queryString = 'INSERT INTO print_list (event_id, photo_id, copies, is_fullfilled, timestamp) VALUES (?, ?, ?, ?, ?)';
			queryString = mysql.format(queryString, params);
			pool.getConnection(function(err, connection){
				if(err){
					winston.error('DB connection error: ' + err);
					feedback.push({
						'type': 'error',
						'message': 'DB connection error: ' + err,
						'photo_id': item.photoId,
						'copies': item.copies
					});
					if(feedback.length === total){
						doFeedback(feedback, res);
					}
					return
				}
				connection.query(queryString, function(err, rows){
					if(err){
						winston.error('DB query error: ' + err);
						feedback.push({
							'type': 'error',
							'message': 'DB query error: ' + err,
							'photo_id': item.photoId,
							'copies': item.copies
						});
						if(feedback.length === total){
							doFeedback(feedback, res);
						}
						return
					}
					connection.release();
					feedback.push({
						'type': 'success',
						'message': 'ok',
						'photo_id': photoId,
						'copies': copies
					})
					if(feedback.length === total){
						doFeedback(feedback, res);
					}
				});
			});
		});

	}else{
		winston.error('ROUT error, can not get eventId or printItems');
		res.status(500).send('ROUT error, can not get eventId or printItems');
	}
	
}

function doFeedback(feedback, res){
	var errors = feedback.filter(function(f){
		return f.type === 'error';
	});
	var statusCode = errors.length === feedback.length ? 500 : 200;
	res.status(statusCode).send(feedback);
}